package cn.t.modules.scheduler.rest;

import cn.t.modules.scheduler.app.ScheduleApp;
import cn.t.modules.scheduler.common.data.R;
import cn.t.modules.scheduler.core.schedule.Scheduler;
import cn.t.modules.scheduler.rest.req.AddDelayMailTaskReq;
import cn.t.modules.scheduler.core.schedule.task.DelayMailTask;
import cn.t.modules.scheduler.rest.req.ClearScheduleHistoryReq;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.ZoneId;

/**
 * @author 陶敏麒
 * @date 2024/3/5 14:58
 */
@RestController
@RequestMapping("/schedule")
public class ScheduleController {
    @Resource
    private ScheduleApp scheduleApp;
    @Resource
    private Scheduler scheduler;

    @PostMapping("/clearHistory")
    public R<Object> clearScheduleHistory(@Validated @RequestBody ClearScheduleHistoryReq req) {
        this.scheduleApp.clearScheduleHistory(req.getExecTime().getTime());
        return R.okWithMsg("指定时间前已经执行过(包含失败的)的数据清理完成");
    }

    @GetMapping("/count")
    public R<Object> queryTaskCount() {
        return R.ok("当前即将执行的任务总数:" + this.scheduleApp.currentTaskCount());
    }

    /**
     * 添加邮件提醒任务
     */
    @PostMapping("/addDelayMailTask")
    public R<Object> addDelayMailTask(@Validated @RequestBody AddDelayMailTaskReq req) {
        // 返回任务id
        var scheduleId = this.scheduler.addTask(new DelayMailTask(new DelayMailTask.MailContent(req.getContent(), req.getToUsers()), req.getTaskName(), req.getExecTime().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()));
        return R.ok(scheduleId);
    }

    /**
     * 取消计划
     */
    @DeleteMapping("/cancel")
    public R<Object> cancelSchedule(@RequestParam String scheduleId) {
        int count = this.scheduleApp.cancelSchedule(scheduleId);
        return R.okWithMsg(count + "个计划取消完成");
    }
}
